package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.cart.entity.UserHolder;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private String REFIX_KEY="ly:cart:";

    public void addCart(Cart cart) {
        String skuId = cart.getSkuId().toString();
//        从ThreadLocal中获取用户id
        String userId = UserHolder.getUserId();
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(REFIX_KEY + userId);
//        原购物车中是否有此商品
        Boolean hasSku = hashOps.hasKey(skuId);
        if(hasSku){
            String cartJsonString = hashOps.get(skuId);
            Cart cartRedis = JsonUtils.toBean(cartJsonString, Cart.class);
            cartRedis.setNum(cartRedis.getNum()+cart.getNum()); //重新计算数量
            hashOps.put(skuId,JsonUtils.toString(cartRedis));
        }else{  //即将添加的商品 在redis购物车中没有
            hashOps.put(skuId,JsonUtils.toString(cart));
        }
    }
//    从redis中获取购物车数据
    public List<Cart> findCartFromRedis() {
//        从ThreadLocal中获取用户id
        String userId = UserHolder.getUserId();
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(REFIX_KEY + userId);
//        获取BoundHash中的所有value值
        List<String> cartListJsonString = hashOps.values();
        List<Cart> cartList = cartListJsonString.stream().map(cartJsonString -> JsonUtils.toBean(cartJsonString, Cart.class)).collect(Collectors.toList());
        return cartList;
    }

    public void mergeCartList(List<Cart> cartList_store) {
        for (Cart cart : cartList_store) {
            this.addCart(cart);
        }
    }
}
